﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System.Threading.Tasks;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.ConfigSdk;
using ThresholdAssistant.Dapper.Extensions;
using ThresholdAssistant.Handler;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.Redis;

namespace ThresholdAssistant.Job
{
    internal class Program
    {
        private static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            //host.UseNacosConf();
            host.UseAutofacService();

            //获取调度中心实例
            var quartz = host.Services.GetService<SchedulerCenter>();
            var lifetime = host.Services.GetService<IHostApplicationLifetime>();
            lifetime.ApplicationStarted.Register(async () =>
            {
                await quartz.StartScheduler(); //项目启动后启动调度中心
            });
            lifetime.ApplicationStopped.Register(() =>
            {
                quartz.StopScheduler();  //项目停止后关闭调度中心
            });
            await host.RunAsync();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
            .UseAppJson()
            .UseWindowsService()
            .UseColumnMap("ThresholdAssistant.WebAPI.Models")
            .UseCsRedis(connectionNames: HardCodeConstant.CsRedisConfigName)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureContainer<ContainerBuilder>(builder => builder.UseAutofac<QuartzInject>())
            .ConfigureServices((context, services) =>
            {
                services.AddHttpClient();
                services.AddHttpContextAccessor();
                //注入调度中心
                services.AddSingleton<SchedulerCenter>();
                //注入Quartz任何工厂及调度工厂
                services.AddSingleton<IJobFactory, CronJobFactory>();
                services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
            });
    }
}